package com.cgydu.controller;

import com.cgydu.annotation.ContentType;
import com.cgydu.utils.Constants;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * projectName: day25_store
 * author: CGY
 * time: 2020/8/26 14:21
 * description:
 */
public class BaseController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码格式
        req.setCharacterEncoding("utf-8");
        //2.分发调用方法
        //method
        // user?method=reg
        String method = req.getParameter("method");

        Class aClass = this.getClass();

        try {
            Method method1 = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);

            //设置一个响应的编码格式
            boolean annotationPresent = method1.isAnnotationPresent(ContentType.class);

            if (annotationPresent) {
                //有
                ContentType annotation = method1.getAnnotation(ContentType.class);
                String value = annotation.value();
                resp.setContentType(value);
            }else{
                //没有
                resp.setContentType("text/html;charset=utf-8");
            }

            //调用方法、并且获取返回值
            Object ret =  method1.invoke(this, req,resp);


            if (ret != null) {

                if (ret.getClass().getSimpleName().equalsIgnoreCase("string")) {
                    //返回结果是字符串

                    //forward:/路径    //redirect：/路径
                    String path = (String) ret;
                    //转发或者重回定向的路径
                    String url = path.substring(path.indexOf(Constants.FLAG)+1);

                    if (path.startsWith(Constants.FORWARD_ACTION))
                    {
                        //转发
                        req.getRequestDispatcher(url).forward(req, resp);
                    }else if (path.startsWith(Constants.REDIRECT_ACTION)){
                        //重定向
                        resp.sendRedirect(url);
                    }
                }else{
                    //返回的实体类或者实体类集合
                    Gson gson = new Gson();
                    String jsonstr = gson.toJson(ret);
                    resp.getWriter().print(jsonstr);
                }


            }
        } catch (Exception e) {
            e.printStackTrace();

            //1.method为null
            //2.method 找到方法
            //3.代码异常
            resp.sendRedirect(req.getContextPath()+"/error/error.jsp");
        }


    }
}
